import hashlib
import random
import time

import requests


class YoudaoTranslator():

    def __init__(self):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
            "Referer": "https://fanyi.youdao.com/",
            "Cookie": "OUTFOX_SEARCH_USER_ID=-873445509@10.108.162.139"
        }
        self.data = {
            "i": None,
            "client": "fanyideskweb",
            "keyfrom": "fanyi.web",
            "salt": None,
            "sign": None,
            "doctype": "json"
        }
        self.url = "http://fanyi.youdao.com/translate?smartresult-dict&smartresult-rule"

    def translate(self, text):
        self.data["i"] = text
        salt = f"{int(time.time() * 1000)}{random.randint(0, 9)}"
        self.data["salt"] = salt
        sign = f"fanyideskweb{text}{salt}6x(ZHw]mwzX#uev70yfw"
        self.data["sign"] = hashlib.md5(sign.encode("utf-8")).hexdigest()
        res = requests.post(self.url, headers=self.headers, data=self.data)
        return res.json()["translateResult"][0][0]["tgt"]


translator = YoudaoTranslator()
print(translator.translate("Hello World"))
